﻿using Metro.Kashikoi.Common;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Collections.Generic;
using System.Collections;

namespace Metro.Kashikoi.Service.Common.Entity
{
    /// <summary>
    /// 
    /// </summary>
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        private static Dictionary<string, IUnityContainer> containers = 
            new Dictionary<string, IUnityContainer>();

        private IUnityContainer container;

        public UnitOfWorkFactory()
            : this(Constants.UnityContainerContextFactory)
        { }

        /// <summary>
        /// Prevents a default instance of the <see cref="UnitOfWorkFactory"/> class from being created.
        /// </summary>
        public UnitOfWorkFactory(string containerName)
        {
            lock ((containers as ICollection).SyncRoot)
            {
                if (!containers.ContainsKey(containerName))
                {
                    var container = new UnityContainer().LoadConfiguration(containerName);
                    containers.Add(containerName, container);
                }
            }
            this.container = containers[containerName];
        }

        #region IUnitOfWorkFactory Members

        /// <summary>
        /// Gets the context.
        /// </summary>
        /// <typeparam name="TService">The type of the service.</typeparam>
        /// <returns>
        /// The instance of the <c>IUnitOfWork</c>.
        /// </returns>
        public IUnitOfWork GetContext<TService>() where TService : class
        {
            return container.Resolve<IUnitOfWork>(typeof(TService).Name);
        }

        #endregion
    }
}
